<template>
  <div>
      <button @click="connectWebSocket">连接WebSocket</button>
      <button @click="sendMessage">发送消息</button>
      <button @click="closeWebSocket">关闭连接</button>
  </div>
</template>

<script>
import WebSocketService from '@/config/WebSocket.js';

export default {
  data() {
      return {
          webSocket: null
      };
  },
  methods: {
      connectWebSocket() {
          this.webSocket = new WebSocketService('ws://localhost:8888?username=lml&password=123456');
          this.webSocket.connect();

          this.webSocket.on('open', () => {
              console.log('在组件中收到连接成功回调');
          });

          this.webSocket.on('message', (data) => {
              console.log('在组件中收到消息:', data);
          });

          this.webSocket.on('close', () => {
              console.log('在组件中收到连接关闭回调');
          });

          this.webSocket.on('error', (error) => {
              console.error('在组件中收到错误回调:', error);
          });
      },
      sendMessage() {
          if (this.webSocket) {
              this.webSocket.send(
                {
                command: 11,
                data:
                  { 
                    chatType:1,
                    cmd:11,
                    content:"Hello World",
                    createTime:1742550451520,
                     from:"1742543820855",
                    groupId:"100",
                    id:"5d5a8766866a487c9291d7f04409f7f1",
                    msgType:0
                  }
                }
              );
          }
      },
      closeWebSocket() {
          if (this.webSocket) {
              this.webSocket.close();
          }
      }
  }
};
</script>